import { QueryPage as _QueryPage } from "~/api/query";
import { request, useMyFetch } from "./base";

type Address = {
  area: string;
  country: string;
  isp_id: string;
  queryIp: string;
  city: string;
  ip: string;
  isp: string;
  county: string;
  region_id: string;
  area_id: string;
  county_id: null | string;
  region: string;
  country_id: string;
  city_id: string;
};

// export async function getIp() {
//   try {
//     const url = "https://www.ip.cn/api/index?ip&type=0";
//     const res = await fetch(url);
//     const { ip } = (await res.json()) ?? {};
//     return ip;
//   } catch (error) {
//     console.error(error);
//     return "";
//   }
// }

export function getAddress() {
  return request<Address>({
    url: "/public/ip",
    method: "get",
  });
}

// export async function useAddress() {
//   return useMyFetch<Address>(`/public/ip?ip=${ip}`);
// }
export function useViews() {
  return useMyFetch<number>("/public/views");
}
export interface Link {
  id?: number;
  name: string;
  link: string;
}
export function useFriendChain() {
  return useMyFetch<Link[]>("/link");
}
export async function addViews() {
  return request<number>({
    url: "/public/addViews",
    method: "get",
  });
}
const RecapchaKey = "6LdBwmYpAAAAAKIhhz99keUKVl9faX7lL_JfiRlC";
export function loadRecapcha() {
  const url = `https://recaptcha.net/recaptcha/api.js?render=${RecapchaKey}`;
  const script = document.createElement("script");
  script.src = url;
  document.body.appendChild(script);
}

function getRecapchaToken() {
  return new Promise<string>((resolve) => {
    // @ts-ignore
    grecaptcha.ready(() => {
      // @ts-ignore
      grecaptcha
        .execute(RecapchaKey, {
          action: "submit",
        })
        .then((token: any) => {
          resolve(token);
          // Add your logic to submit to your backend server here.
        });
    });
  });
}

interface TransfromFileType {
  file: File;
  type: string;
  quality: number;
}
export async function transfromFile(param: TransfromFileType) {
  if (process.server) return Promise.reject("不支持服务端调用");
  const { file, type, quality } = param;
  const token = await getRecapchaToken();
  const fingerprint = await getFingerPrint();
  const formData = new FormData();
  formData.append("file", file);
  formData.append("type", type);
  formData.append("fingerprint", fingerprint);
  formData.append("token", token);
  formData.append("quality", quality.toString());
  return request<{ url: string }>({
    url: "/file/transfrom",
    method: "post",
    data: formData,
  });
}
